import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'dart:async';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'dart:math' as math;
import 'package:shared_preferences/shared_preferences.dart';

class CameraPage extends StatefulWidget {
  final BluetoothDevice? device;
  final Function(String) onVideoNameReceived;
  final bool autoMode;
  final bool startRecordingImmediately;
  final String? initialVideoName;  // 添加初始视频名称参数
  final List<CameraDescription>? cameras;

  const CameraPage({
    super.key,
    this.device,
    required this.onVideoNameReceived,
    this.autoMode = true,
    this.startRecordingImmediately = false,
    this.initialVideoName,  // 添加到构造函数
    this.cameras,
  });

  @override
  State<CameraPage> createState() => CameraPageState();
}

class CameraPageState extends State<CameraPage> with TickerProviderStateMixin {
  CameraController? _controller;
  final ValueNotifier<bool> _isRecording = ValueNotifier<bool>(false);
  final ValueNotifier<String> _recordingTime = ValueNotifier<String>('00:00');
  bool _isFrontCamera = false;
  String? _videoPath;
  DateTime? _startTime;
  Timer? _timer;
  late AnimationController _pulseController;
  late AnimationController _focusAnimationController;
  late Animation<double> _focusAnimation;
  bool _isInitialized = false;
  Size? _previewSize;

  // 添加对焦和变焦相关变量
  double _minAvailableZoom = 1.0;
  double _maxAvailableZoom = 1.0;
  double _currentZoomLevel = 1.0;
  double _baseScale = 1.0;
  Offset? _focusPoint;
  Timer? _focusTimer;
  bool _isFocusing = false;

  // 添加蓝牙相关变量
  BluetoothCharacteristic? _characteristic;
  StreamSubscription<List<int>>? _subscription;

  String? _pendingVideoName;  // 添加待处理的视频名称变量

  // 添加手势状态变量
  bool _isScaling = false;
  Timer? _tapTimer;
  int _pointerCount = 0;  // 添加手指数量计数

  // 添加清晰度相关变量
  ResolutionPreset _currentResolution = ResolutionPreset.max;
  final Map<ResolutionPreset, String> _resolutionMap = {
    ResolutionPreset.max: '最高清晰度',
    ResolutionPreset.ultraHigh: '超清 4K',
    ResolutionPreset.veryHigh: '超清 2K',
    ResolutionPreset.high: '高清 1080P',
    ResolutionPreset.medium: '标清 720P',
  };

  // 添加曝光相关变量
  double _currentExposureOffset = 0.0;
  double _minAvailableExposure = -1.0;
  double _maxAvailableExposure = 1.0;
  bool _isExposureAdjusting = false;

  // 添加自动对焦和曝光优化相关变量
  Timer? _autoOptimizationTimer;

  // 添加持久化相关方法
  Future<void> _loadSavedResolution() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final savedResolution = prefs.getString('camera_resolution');
      if (savedResolution != null) {
        _currentResolution = ResolutionPreset.values.firstWhere(
          (preset) => preset.toString() == savedResolution,
          orElse: () => ResolutionPreset.max,
        );
      }
    } catch (e) {
      debugPrint('加载清晰度设置失败: $e');
    }
  }

  Future<void> _saveResolution(ResolutionPreset resolution) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('camera_resolution', resolution.toString());
    } catch (e) {
      debugPrint('保存清晰度设置失败: $e');
    }
  }

  @override
  void initState() {
    super.initState();
    _pulseController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1000),
    );
    
    // 初始化对焦动画
    _focusAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );
    
    _focusAnimation = TweenSequence<double>([
      TweenSequenceItem(
        tween: Tween<double>(begin: 1.2, end: 1.0)
            .chain(CurveTween(curve: Curves.easeOutCubic)),
        weight: 50.0,
      ),
      TweenSequenceItem(
        tween: Tween<double>(begin: 1.0, end: 0.95)
            .chain(CurveTween(curve: Curves.easeInOut)),
        weight: 25.0,
      ),
      TweenSequenceItem(
        tween: Tween<double>(begin: 0.95, end: 1.0)
            .chain(CurveTween(curve: Curves.easeOut)),
        weight: 25.0,
      ),
    ]).animate(_focusAnimationController);
    
    // 设置初始视频名称
    _pendingVideoName = widget.initialVideoName;
    
    _loadSavedResolution().then((_) => _initializeCamera());
    if (widget.device != null) {
      _initializeBluetooth();
    }
  }

  Future<void> _initializeCamera() async {
    try {
      await _requestPermissions();
      
      final cameras = await availableCameras();
      final back = cameras.firstWhere(
        (camera) => camera.lensDirection == CameraLensDirection.back,
        orElse: () => cameras.first,
      );

      _controller = CameraController(
        back,
        _currentResolution,
        enableAudio: true,
        imageFormatGroup: Platform.isAndroid ? ImageFormatGroup.jpeg : ImageFormatGroup.bgra8888,
      );

      await _controller!.initialize();
      
      // 获取相机支持的最佳预览尺寸
      final previewSize = _controller!.value.previewSize!;
      debugPrint('相机预览尺寸: ${previewSize.width} x ${previewSize.height}');
      final screenSize = MediaQuery.of(context).size;
      debugPrint('屏幕尺寸: ${screenSize.width} x ${screenSize.height}');
      
      // 计算最佳显示比例
      final screenRatio = screenSize.width / screenSize.height;
      final previewRatio = previewSize.width / previewSize.height;
      debugPrint('屏幕比例: $screenRatio, 预览比例: $previewRatio');
      
      // 设置相机参数
      await Future.wait([
        // 初始化变焦范围
        _controller!.getMaxZoomLevel().then((value) => _maxAvailableZoom = value),
        _controller!.getMinZoomLevel().then((value) => _minAvailableZoom = value),
        // 设置自动对焦模式，使用正确的常量
        _controller!.setFocusMode(FocusMode.auto),
        // 设置自动曝光模式，使用正确的常量
        _controller!.setExposureMode(ExposureMode.auto),
        // 确保闪光灯关闭
        _controller!.setFlashMode(FlashMode.off),
      ]);

      // 获取曝光范围
      try {
        // 尝试获取最小曝光补偿
        _controller!.getMinExposureOffset().then((value) {
          _minAvailableExposure = value;
          debugPrint('最小曝光值: $_minAvailableExposure');
        });
        
        // 尝试获取最大曝光补偿
        _controller!.getMaxExposureOffset().then((value) {
          _maxAvailableExposure = value;
          debugPrint('最大曝光值: $_maxAvailableExposure');
        });
      } catch (e) {
        debugPrint('获取曝光范围失败: $e');
        // 使用默认值
        _minAvailableExposure = -1.0;
        _maxAvailableExposure = 1.0;
      }

      // 设置预览尺寸
      if (mounted) {
        setState(() {
          _isInitialized = true;
          _previewSize = previewSize;
        });

        // 如果设置了自动开始录制，则在初始化完成后立即开始录制
        if (widget.startRecordingImmediately && !_isRecording.value) {
          startRecording();
        }
        
        // 启动自动对焦和曝光优化
        _startAutoFocusAndExposureOptimization();
      }
    } catch (e) {
      _showErrorDialog('初始化失败: $e');
    }
  }

  Future<void> _requestPermissions() async {
    bool allGranted = false;
    
    while (!allGranted) {
      // 请求所有必要的权限
      Map<Permission, PermissionStatus> statuses = await [
        Permission.storage,
        Permission.camera,
        Permission.microphone,
      ].request();

      // 检查权限
      allGranted = true;
      List<Permission> deniedPermissions = [];
      
      statuses.forEach((permission, status) {
        if (!status.isGranted) {
          allGranted = false;
          deniedPermissions.add(permission);
        }
      });

      if (!allGranted) {
        // 显示权限请求对话框
        bool shouldRetry = await showCupertinoDialog<bool>(
          context: context,
          barrierDismissible: false,
          builder: (context) => CupertinoAlertDialog(
            title: const Text('需要开启权限'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text('请按以下步骤操作：'),
                const SizedBox(height: 16),
                const Text('1. 点击下方"去设置"按钮', style: TextStyle(fontSize: 14)),
                const Text('2. 在应用信息页面中点击"权限管理"', style: TextStyle(fontSize: 14)),
                const SizedBox(height: 8),
                ...deniedPermissions.map((permission) => Padding(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: Row(
                    children: [
                      Container(
                        width: 8,
                        height: 8,
                        decoration: const BoxDecoration(
                          color: Colors.blue,
                          shape: BoxShape.circle,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          '找到"${_getPermissionName(permission)}"并点击"允许"',
                          style: const TextStyle(fontSize: 14),
                        ),
                      ),
                    ],
                  ),
                )),
                const SizedBox(height: 8),
                const Text('3. 返回应用继续使用', style: TextStyle(fontSize: 14)),
                Container(
                  margin: const EdgeInsets.only(top: 16),
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFFF3E0),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Column(
                    children: [
                      Text(
                        '特别说明：',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                          color: Colors.orange,
                        ),
                      ),
                      Text(
                        '如果找不到某些权限选项，请点击右上角"更多"或"⋮"，选择"显示全部权限"',
                        style: TextStyle(fontSize: 13, color: Colors.orange),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            actions: [
              CupertinoDialogAction(
                child: const Text('退出'),
                onPressed: () {
                  Navigator.pop(context, false);
                  Navigator.pop(context);
                },
              ),
              CupertinoDialogAction(
                isDefaultAction: true,
                child: const Text('去设置'),
                onPressed: () async {
                  Navigator.pop(context, true);
                  await openAppSettings();
                },
              ),
            ],
          ),
        ) ?? false;

        if (!shouldRetry) {
          throw '需要必要的权限才能继续使用';
        }
        
        // 等待用户从设置页面返回
        await Future.delayed(const Duration(seconds: 1));
      }
    }

    // 创建存储目录
    try {
      final String videoDirectory = '/storage/emulated/0/DCIM/XAI/record';
      final dir = Directory(videoDirectory);
      if (!await dir.exists()) {
        await dir.create(recursive: true);
      }
    } catch (e) {
      _showErrorDialog('创建存储目录失败，请确保已允许存储权限');
      throw '创建存储目录失败: $e';
    }
  }

  String _getPermissionName(Permission permission) {
    switch (permission) {
      case Permission.camera:
        return '相机';
      case Permission.microphone:
        return '麦克风';
      case Permission.storage:
        return '存储空间';
      default:
        return permission.toString();
    }
  }

  void _showErrorDialog(String message) {
    showCupertinoDialog(
      context: context,
      builder: (context) => CupertinoAlertDialog(
        title: const Text('错误'),
        content: Text(message),
        actions: [
          CupertinoDialogAction(
            child: const Text('确定'),
            onPressed: () => Navigator.pop(context),
          ),
        ],
      ),
    );
  }

  void _startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted && _startTime != null) {
        final duration = DateTime.now().difference(_startTime!);
        _recordingTime.value = 
            '${duration.inMinutes.toString().padLeft(2, '0')}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
      }
    });
  }

  void _stopTimer() {
    _timer?.cancel();
    _timer = null;
    _recordingTime.value = '00:00';
  }

  // 获取不重复的文件路径
  Future<String> _getNonDuplicateFilePath(String baseFilePath) async {
    if (!await File(baseFilePath).exists()) {
      return baseFilePath;
    }

    final extension = path.extension(baseFilePath);
    final pathWithoutExtension = baseFilePath.substring(
      0,
      baseFilePath.length - extension.length,
    );

    int counter = 1;
    String newPath;
    do {
      newPath = '$pathWithoutExtension-$counter$extension';
      counter++;
    } while (await File(newPath).exists());

    return newPath;
  }

  Future<String> _getVideoFilePath() async {
    try {
      final String videoDirectory = '/storage/emulated/0/DCIM/xai/record';
      final dir = Directory(videoDirectory);
      if (!await dir.exists()) {
        await dir.create(recursive: true);
      }
      
      // 生成自动文件名
      final String fileName = _generateAutoFileName();
      final String filePath = path.join(videoDirectory, '$fileName.mp4');
      
      // 获取不重复的文件路径
      return _getNonDuplicateFilePath(filePath);
    } catch (e) {
      throw '创建视频目录失败: $e';
    }
  }

  String _generateAutoFileName() {
    final now = DateTime.now();
    return 'VID_${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}_${now.hour.toString().padLeft(2, '0')}${now.minute.toString().padLeft(2, '0')}${now.second.toString().padLeft(2, '0')}';
  }

  Future<void> _initializeBluetooth() async {
    if (widget.device == null) return;

    try {
      // 显示蓝牙连接状态
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Row(
              children: [
                CupertinoActivityIndicator(),
                SizedBox(width: 12),
                Text('正在初始化蓝牙连接...'),
              ],
            ),
            duration: Duration(seconds: 2),
          ),
        );
      }

      // 确保设备已连接
      if (!await widget.device!.isConnected) {
        await widget.device!.connect(timeout: const Duration(seconds: 10));
      }

      // 监听连接状态
      widget.device!.connectionState.listen((BluetoothConnectionState state) {
        if (state == BluetoothConnectionState.disconnected) {
          _handleDisconnection();
        }
      });

      List<BluetoothService> services = await widget.device!.discoverServices();
      bool foundService = false;

      for (var service in services) {
        for (var characteristic in service.characteristics) {
          if (characteristic.properties.notify && characteristic.properties.write) {
            _characteristic = characteristic;
            await characteristic.setNotifyValue(true);
            
            // 设置通知监听
            _subscription?.cancel();
            _subscription = characteristic.value.listen(
              (value) {
                if (value.isNotEmpty) {
                  String command = String.fromCharCodes(value);
                  handleCommand(command);
                }
              },
              onError: (error) {
                debugPrint('蓝牙通知错误: $error');
                _handleBluetoothError(error);
              },
            );
            
            foundService = true;
            
            // 发送初始状态
            await _sendStatus();
            
            // 显示蓝牙连接成功
            if (mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Row(
                    children: [
                      const Icon(Icons.bluetooth_connected, color: Colors.white),
                      const SizedBox(width: 12),
                      Text('已连接到: ${widget.device!.platformName}'),
                    ],
                  ),
                  backgroundColor: Colors.green.withOpacity(0.8),
                  duration: const Duration(seconds: 2),
                ),
              );
            }
            break;
          }
        }
        if (foundService) break;
      }

      if (!foundService) {
        throw '未找到可用的蓝牙服务';
      }
    } catch (e) {
      debugPrint('蓝牙初始化错误: $e');
      _handleBluetoothError(e);
    }
  }

  Future<void> _handleDisconnection() async {
    debugPrint('蓝牙连接断开');
    _subscription?.cancel();
    _characteristic = null;

    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Row(
            children: [
              Icon(Icons.bluetooth_disabled, color: Colors.white),
              SizedBox(width: 12),
              Text('蓝牙连接已断开'),
            ],
          ),
          backgroundColor: Colors.orange,
          duration: Duration(seconds: 2),
        ),
      );

      // 尝试重新连接
      try {
        await _initializeBluetooth();
      } catch (e) {
        debugPrint('重新连接失败: $e');
      }
    }
  }

  void _handleBluetoothError(dynamic error) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              const Icon(Icons.error_outline, color: Colors.white),
              const SizedBox(width: 12),
              Expanded(
                child: Text(
                  '蓝牙错误: ${error.toString()}',
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          backgroundColor: Colors.red.withOpacity(0.8),
          duration: const Duration(seconds: 3),
        ),
      );
    }
  }

  void handleCommand(String command) {
    debugPrint('相机页面收到命令: $command');
    
    if (command.startsWith('START_RECORDING:')) {
      // 从命令中提取视频名称
      final videoName = command.substring('START_RECORDING:'.length);
      debugPrint('收到开始录制命令，视频名称: $videoName');
      
      if (!_isRecording.value) {
        _pendingVideoName = videoName;  // 保存视频名称
        _toggleRecording();  // 开始录制
      }
    } else {
      switch (command.trim().toUpperCase()) {
        case 'START_RECORDING':
          if (!_isRecording.value) {
            _toggleRecording();
          }
          break;
          
        case 'STOP_RECORDING':
          if (_isRecording.value) {
            _toggleRecording();
          }
          break;
        
        case 'SWITCH_CAMERA':
          _switchCamera();
          break;
      }
    }
  }

  Future<void> _sendBluetoothResponse(String message) async {
    if (_characteristic != null) {
      try {
        await _characteristic!.write(utf8.encode(message));
        debugPrint('蓝牙响应发送成功: $message');
      } catch (e) {
        debugPrint('蓝牙响应发送失败: $e');
      }
    }
  }

  Future<void> _sendStatus() async {
    final status = {
      'isRecording': _isRecording.value,
      'recordingTime': _recordingTime.value,
      'isFrontCamera': _isFrontCamera,
    };
    await _sendBluetoothResponse('STATUS:${jsonEncode(status)}');
  }

  Future<void> _switchCamera() async {
    if (_controller == null || !_isInitialized) return;

    final cameras = await availableCameras();
    final newCamera = _isFrontCamera
        ? cameras.firstWhere(
            (camera) => camera.lensDirection == CameraLensDirection.back,
            orElse: () => cameras.first)
        : cameras.firstWhere(
            (camera) => camera.lensDirection == CameraLensDirection.front,
            orElse: () => cameras.first);

    // 保存当前录制状态
    final wasRecording = _isRecording.value;
    if (wasRecording) {
      await _toggleRecording(); // 停止录制
    }

    // 释放当前相机控制器
    await _controller?.dispose();

    // 初始化新相机
    _controller = CameraController(
      newCamera,
      ResolutionPreset.max,
      enableAudio: true,
      imageFormatGroup: ImageFormatGroup.jpeg,
    );

    try {
      await _controller!.initialize();
      await Future.wait([
        _controller!.getMaxZoomLevel().then((value) => _maxAvailableZoom = value),
        _controller!.getMinZoomLevel().then((value) => _minAvailableZoom = value),
        _controller!.setFocusMode(FocusMode.auto),
        _controller!.setFlashMode(FlashMode.off), // 确保闪光灯关闭
      ]);
      
      _isFrontCamera = !_isFrontCamera;
      
      if (mounted) {
        setState(() {
          _isInitialized = true;
          _previewSize = _controller!.value.previewSize;
        });
      }

      // 如果之前在录制，切换后继续录制
      if (wasRecording && mounted) {
        await _toggleRecording();
      }
    } catch (e) {
      _showErrorDialog('切换相机失败: $e');
    }
  }

  void _showSaveSuccessToast(String fileName) {
    if (!mounted) return;
    
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      
      // 创建一个覆盖层
      final overlay = OverlayEntry(
        builder: (context) => Positioned(
          top: MediaQuery.of(context).padding.top + 50,
          left: 16,
          right: 16,
          child: Material(
            color: Colors.transparent,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                color: CupertinoColors.systemGreen.withOpacity(0.9),
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 10,
                    offset: const Offset(0, 5),
                  ),
                ],
              ),
              child: Row(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      shape: BoxShape.circle,
                    ),
                    child: const Icon(
                      CupertinoIcons.checkmark_circle,
                      color: Colors.white,
                      size: 20,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '视频保存成功',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        const SizedBox(height: 2),
                        Text(
                          fileName,
                          style: TextStyle(
                            color: Colors.white.withOpacity(0.9),
                            fontSize: 13,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );

      // 显示覆盖层
      Overlay.of(context).insert(overlay);

      // 2秒后移除
      Future.delayed(const Duration(seconds: 2), () {
        overlay.remove();
      });
    });
  }

  Future<void> _toggleRecording() async {
    if (_controller == null || !_controller!.value.isInitialized) {
      debugPrint('相机未初始化');
      return;
    }

    try {
      if (_isRecording.value) {
        debugPrint('停止录制...');
        final XFile video = await _controller!.stopVideoRecording();
        final String targetPath = await _getVideoFilePath();
        
        final File sourceFile = File(video.path);
        if (await sourceFile.exists()) {
          await sourceFile.copy(targetPath);
          await sourceFile.delete();
          
          _videoPath = targetPath;
          _isRecording.value = false;
          _timer?.cancel();
          _timer = null;
          _pulseController.stop();

          // 发送视频名称给蓝牙主设备
          final fileName = path.basename(_videoPath!);
          widget.onVideoNameReceived(fileName);
          _showSaveSuccessToast(fileName);
        }
      } else {
        debugPrint('开始录制...');
        await _controller!.startVideoRecording();
        _isRecording.value = true;
        _startTime = DateTime.now();
        _startTimer();
        _pulseController.repeat();
      }
    } catch (e) {
      debugPrint('录制操作失败: $e');
      _showError('录制操作失败: ${e.toString()}');
    }
  }

  // 开始录制
  Future<void> startRecording() async {
    if (!_isInitialized || _isRecording.value) return;

    try {
      await _controller!.startVideoRecording();
      _isRecording.value = true;
      _startTime = DateTime.now();
      _startTimer();
      _pulseController.repeat();
    } catch (e) {
      debugPrint('开始录制错误: $e');
      _showError('开始录制失败: $e');
    }
  }

  // 带文件名的停止录制方法
  Future<void> stopRecordingWithName(String videoName) async {
    if (!_isInitialized || !_isRecording.value) return;

    try {
      final file = await _controller!.stopVideoRecording();
      _isRecording.value = false;
      
      // 使用传入的视频名称
      final String targetPath = await _getVideoFilePathWithName(videoName);
      final File sourceFile = File(file.path);
      if (await sourceFile.exists()) {
        await sourceFile.copy(targetPath);
        await sourceFile.delete();
        
        _videoPath = targetPath;
        _timer?.cancel();
        _pulseController.stop();
        _recordingTime.value = '00:00';

        // 通知视频名称
        widget.onVideoNameReceived(videoName);
        
        // 显示保存成功提示
        _showSaveSuccessToast(path.basename(targetPath));
      }
    } catch (e) {
      debugPrint('停止录制错误: $e');
      _showError('停止录制失败: $e');
    }
  }

  // 获取指定名称的视频文件路径
  Future<String> _getVideoFilePathWithName(String fileName) async {
    try {
      final String videoDirectory = '/storage/emulated/0/DCIM/xai/record';
      final dir = Directory(videoDirectory);
      if (!await dir.exists()) {
        await dir.create(recursive: true);
      }
      
      final String filePath = path.join(videoDirectory, '$fileName.mp4');
      
      // 获取不重复的文件路径
      return _getNonDuplicateFilePath(filePath);
    } catch (e) {
      throw '创建视频目录失败: $e';
    }
  }

  // 添加带名称的开始录制方法
  Future<void> startRecordingWithName(String videoName) async {
    _pendingVideoName = videoName;
    await startRecording();
  }

  void _showError(String message) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  // 停止录制
  Future<void> stopRecording() async {
    if (!_isInitialized || !_isRecording.value) return;

    try {
      final file = await _controller!.stopVideoRecording();
      _isRecording.value = false;
      
      // 获取目标路径并复制文件
      final String targetPath = await _getVideoFilePath();
      final File sourceFile = File(file.path);
      if (await sourceFile.exists()) {
        await sourceFile.copy(targetPath);
        await sourceFile.delete();
        
        _videoPath = targetPath;
        _timer?.cancel();
        _pulseController.stop();
        _recordingTime.value = '00:00';

        // 生成视频文件名并通知
        final fileName = path.basename(targetPath);
        widget.onVideoNameReceived(fileName.replaceAll('.mp4', ''));
        
        // 显示保存成功提示
        _showSaveSuccessToast(fileName);
      }
    } catch (e) {
      debugPrint('停止录制错误: $e');
      _showError('停止录制失败: $e');
    }
  }

  @override
  void dispose() {
    _subscription?.cancel();
    if (widget.device != null) {
      widget.device!.disconnect();
    }
    _pulseController.dispose();
    _timer?.cancel();
    _controller?.dispose();
    _isRecording.dispose();
    _recordingTime.dispose();
    _autoOptimizationTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!_isInitialized || _previewSize == null) {
      return Scaffold(
        backgroundColor: Colors.black,
        body: Container(
          color: Colors.black,
          child: const Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                CupertinoActivityIndicator(color: Colors.white),
                SizedBox(height: 16),
                Text('初始化相机...', 
                  style: TextStyle(color: Colors.white)),
              ],
            ),
          ),
        ),
      );
    }

    // 计算预览尺寸
    final size = MediaQuery.of(context).size;
    final deviceRatio = size.width / size.height;
    final previewRatio = _previewSize!.height / _previewSize!.width;

    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Stack(
          children: [
            // 修改这里，使用 GestureDetector 包装相机预览
            Container(
              color: Colors.black,
              child: Center(
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    final previewSize = _controller!.value.previewSize!;
                    final screenSize = MediaQuery.of(context).size;
                    
                    // 计算最佳缩放比例以填充屏幕
                    final scale = math.max(
                      constraints.maxWidth / previewSize.width,
                      constraints.maxHeight / previewSize.height,
                    );
                    
                    // 计算缩放后的尺寸
                    final scaledWidth = previewSize.width * scale;
                    final scaledHeight = previewSize.height * scale;
                    
                    return ClipRect(
                      child: Transform.scale(
                        scale: scale,
                        child: Center(
                          child: SizedBox(
                            width: previewSize.width,
                            height: previewSize.height,
                            child: Listener(
                              onPointerDown: _handlePointerDown,
                              onPointerUp: _handlePointerUp,
                              child: GestureDetector(
                                onTapDown: _handleTapDown,
                                onScaleStart: _handleScaleStart,
                                onScaleUpdate: _handleScaleUpdate,
                                onScaleEnd: _handleScaleEnd,
                                // 添加曝光调整手势
                                onVerticalDragStart: (_) => setState(() => _isExposureAdjusting = true),
                                onVerticalDragEnd: (_) => setState(() => _isExposureAdjusting = false),
                                onVerticalDragUpdate: _onExposureDragUpdate,
                                child: CameraPreview(_controller!),
                              ),
                            ),
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
            
            // 对焦框
            _buildFocusMarker(),
            
            // 变焦指示器
            _buildZoomIndicator(),
            
            // 修改曝光调整指示器
            if (_isExposureAdjusting)
              Positioned(
                right: 20,
                top: MediaQuery.of(context).size.height * 0.2, // 从屏幕20%的位置开始
                bottom: MediaQuery.of(context).size.height * 0.2, // 到屏幕80%的位置结束
                child: Container(
                  width: 30,
                  decoration: BoxDecoration(
                    color: Colors.black45,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.add, color: Colors.white, size: 18),
                      SizedBox(height: 8),
                      Expanded(
                        child: LayoutBuilder(
                          builder: (context, constraints) {
                            final barHeight = constraints.maxHeight * 0.7; // 使用可用高度的70%
                            return Container(
                              height: barHeight,
                              width: 3,
                              decoration: BoxDecoration(
                                color: Colors.white70,
                                borderRadius: BorderRadius.circular(1.5),
                              ),
                              alignment: Alignment.bottomCenter,
                              child: Container(
                                height: barHeight * ((_currentExposureOffset - _minAvailableExposure) / 
                                    (_maxAvailableExposure - _minAvailableExposure)),
                                width: 3,
                                color: Colors.yellow,
                              ),
                            );
                          }
                        ),
                      ),
                      SizedBox(height: 8),
                      Icon(Icons.remove, color: Colors.white, size: 18),
                      SizedBox(height: 12),
                      Container(
                        padding: EdgeInsets.symmetric(vertical: 4, horizontal: 6),
                        decoration: BoxDecoration(
                          color: Colors.black54,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: Text(
                          '${_currentExposureOffset.toStringAsFixed(1)}',
                          style: TextStyle(color: Colors.white, fontSize: 12),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            
            // Top Controls with smaller font sizes
            Positioned(
              top: 16,
              left: 16,
              right: 16,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  CupertinoButton(
                    padding: EdgeInsets.zero,
                    child: const Icon(CupertinoIcons.xmark,
                        color: Colors.white, size: 24),
                    onPressed: () => Navigator.pop(context),
                  ),
                  ValueListenableBuilder<bool>(
                    valueListenable: _isRecording,
                    builder: (context, isRecording, child) {
                      if (!isRecording) {
                        return CupertinoButton(
                          padding: EdgeInsets.zero,
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.black45,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Row(
                              children: [
                                Text(
                                  _resolutionMap[_currentResolution]!,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                  ),
                                ),
                                const SizedBox(width: 2),
                                const Icon(
                                  CupertinoIcons.chevron_down,
                                  color: Colors.white,
                                  size: 12,
                                ),
                              ],
                            ),
                          ),
                          onPressed: _showResolutionPicker,
                        );
                      }
                      return ValueListenableBuilder<String>(
                        valueListenable: _recordingTime,
                        builder: (context, time, child) {
                          return Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.black45,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                AnimatedBuilder(
                                  animation: _pulseController,
                                  builder: (context, child) {
                                    return Container(
                                      width: 6,
                                      height: 6,
                                      decoration: BoxDecoration(
                                        color: Colors.red.withOpacity(
                                          0.5 + 0.5 * _pulseController.value),
                                        shape: BoxShape.circle,
                                      ),
                                    );
                                  },
                                ),
                                const SizedBox(width: 6),
                                Text(
                                  time,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 13,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      );
                    },
                  ),
                  CupertinoButton(
                    padding: EdgeInsets.zero,
                    child: const Icon(
                      CupertinoIcons.camera_rotate,
                      color: Colors.white,
                      size: 24
                    ),
                    onPressed: _isRecording.value ? null : _switchCamera,
                  ),
                ],
              ),
            ),
            
            // Bottom Controls
            Positioned(
              bottom: 32,
              left: 0,
              right: 0,
              child: ValueListenableBuilder<bool>(
                valueListenable: _isRecording,
                builder: (context, isRecording, child) {
                  return Container(
                    color: Colors.transparent,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        RepaintBoundary(
                          child: GestureDetector(
                            onTap: _toggleRecording,
                            child: Container(
                              width: isRecording ? 72 : 80,
                              height: isRecording ? 72 : 80,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                border: Border.all(
                                  color: Colors.white,
                                  width: isRecording ? 3 : 4,
                                ),
                                color: isRecording ? Colors.red.withOpacity(0.8) : Colors.transparent,
                              ),
                              child: Center(
                                child: Container(
                                  width: isRecording ? 32 : 60,
                                  height: isRecording ? 32 : 60,
                                  decoration: BoxDecoration(
                                    shape: isRecording ? BoxShape.rectangle : BoxShape.circle,
                                    borderRadius: isRecording ? BorderRadius.circular(8) : null,
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 修改对焦方法
  Future<void> _handleFocusTap(TapDownDetails details) async {
    if (_controller == null || !_controller!.value.isInitialized) return;

    // 取消之前的对焦计时器
    _focusTimer?.cancel();
    
    // 立即更新对焦点位置
    final size = MediaQuery.of(context).size;
    
    // 计算对焦点相对于预览的位置
    final RenderBox box = context.findRenderObject() as RenderBox;
    final Offset localPoint = box.globalToLocal(details.globalPosition);
    
    // 考虑 SafeArea 和 AspectRatio 的影响
    final double previewHeight = size.width * 16 / 9; // 因为我们使用了 16:9 的比例
    final double yOffset = (size.height - previewHeight) / 2;
    
    // 调整后的坐标
    double x = localPoint.dx / size.width;
    double y = (localPoint.dy - yOffset) / previewHeight;
    
    // 确保坐标在 0-1 范围内
    x = x.clamp(0.0, 1.0);
    y = y.clamp(0.0, 1.0);
    
    // 设置对焦点
    setState(() {
      _focusPoint = localPoint;
      // 重置并启动对焦动画
      _focusAnimationController.reset();
      _focusAnimationController.forward();
    });
    
    try {
      // 先设置对焦模式为自动对焦
      await _controller!.setFocusMode(FocusMode.auto);
      
      // 设置对焦点
      await _controller!.setFocusPoint(Offset(x, y));
      
      // 设置曝光模式为自动曝光
      await _controller!.setExposureMode(ExposureMode.auto);
      
      // 设置测光点，以获得更好的曝光
      await _controller!.setExposurePoint(Offset(x, y));
      
      // 等待对焦和曝光调整完成
      await Future.delayed(const Duration(milliseconds: 800));
      
      // 进行多次对焦尝试，以获得最佳效果
      for (int i = 0; i < 2; i++) {
        await _controller!.setFocusMode(FocusMode.auto);
        await Future.delayed(const Duration(milliseconds: 300));
      }
      
      // 短暂延迟后，切换到自动对焦模式以保持清晰
      if (_controller != null && mounted) {
        // 使用正确的对焦模式
        await _controller!.setFocusMode(FocusMode.auto);
        await _controller!.setExposureMode(ExposureMode.auto);
      }
      
      // 对焦点显示动画效果，2秒后自动消失
      _focusTimer = Timer(const Duration(seconds: 2), () {
        if (mounted) {
          setState(() {
            _focusPoint = null;
          });
        }
      });
      
      debugPrint('对焦和曝光优化完成');
    } catch (e) {
      debugPrint('设置对焦点失败: $e');
    }
  }

  // 修改处理点击的方法，确保即使在缩放时也能响应对焦
  Future<void> _handleTapDown(TapDownDetails details) async {
    // 如果有多个手指，不处理点击
    if (_pointerCount > 1) return;
    
    // 即使在缩放状态也允许对焦
    _handleFocusTap(details);
    
    // 如果正在缩放，重置缩放状态
    if (_isScaling) {
      _tapTimer?.cancel();
      _tapTimer = Timer(const Duration(milliseconds: 200), () {
        _isScaling = false;
      });
    }
  }

  // 处理缩放手势
  void _handleScaleStart(ScaleStartDetails details) {
    _isScaling = true;
    _baseScale = _currentZoomLevel;
    _tapTimer?.cancel();
  }

  Future<void> _handleScaleUpdate(ScaleUpdateDetails details) async {
    if (_controller == null || !_controller!.value.isInitialized) return;

    // 只有当缩放比例不为1时才处理缩放
    if (details.scale != 1.0) {
      // 计算新的缩放级别
      double newScale = (_baseScale * details.scale).clamp(_minAvailableZoom, _maxAvailableZoom);
      
      if (newScale != _currentZoomLevel) {
        setState(() => _currentZoomLevel = newScale);
        
        try {
          await _controller!.setZoomLevel(newScale);
        } catch (e) {
          debugPrint('设置变焦失败: $e');
        }
      }
    }
  }

  void _handleScaleEnd(ScaleEndDetails details) {
    _tapTimer = Timer(const Duration(milliseconds: 300), () {
      _isScaling = false;
    });
  }

  // 显示对焦框
  Widget _buildFocusMarker() {
    if (_focusPoint == null) return const SizedBox.shrink();

    return Positioned(
      left: _focusPoint!.dx - 35,
      top: _focusPoint!.dy - 35,
      child: AnimatedBuilder(
        animation: _focusAnimationController,
        builder: (context, child) {
          return Transform.scale(
            scale: _focusAnimation.value,
            child: Stack(
              alignment: Alignment.center,
              children: [
                // 外圈
                Container(
                  width: 70,
                  height: 70,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.white.withOpacity(0.8),
                      width: 1,
                    ),
                    borderRadius: BorderRadius.circular(35),
                  ),
                ),
                // 内圈
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.white.withOpacity(0.6),
                      width: 1,
                    ),
                    borderRadius: BorderRadius.circular(30),
                  ),
                ),
                // 中心十字
                CustomPaint(
                  size: const Size(40, 40),
                  painter: FocusMarkerPainter(
                    color: Colors.white.withOpacity(0.9),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  // 显示变焦指示器
  Widget _buildZoomIndicator() {
    return Positioned(
      right: 16,
      top: MediaQuery.of(context).padding.top + 80,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.black54,
          borderRadius: BorderRadius.circular(20),
        ),
        child: Text(
          '${_currentZoomLevel.toStringAsFixed(1)}x',
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  // 添加手指数量跟踪
  void _handlePointerDown(PointerDownEvent event) {
    _pointerCount++;
  }

  void _handlePointerUp(PointerUpEvent event) {
    _pointerCount--;
    if (_pointerCount < 0) _pointerCount = 0;
  }

  // 修改切换清晰度的方法
  Future<void> _changeResolution(ResolutionPreset newResolution) async {
    if (_controller == null || newResolution == _currentResolution) return;

    // 保存当前录制状态
    final wasRecording = _isRecording.value;
    if (wasRecording) {
      await _toggleRecording();
    }

    // 保存当前相机方向
    final currentCamera = _controller!.description;
    
    // 释放当前控制器
    await _controller?.dispose();
    
    // 使用新的分辨率创建控制器
    _controller = CameraController(
      currentCamera,
      newResolution,
      enableAudio: true,
      imageFormatGroup: Platform.isAndroid ? ImageFormatGroup.jpeg : ImageFormatGroup.bgra8888,
    );

    try {
      await _controller!.initialize();
      await Future.wait([
        _controller!.getMaxZoomLevel().then((value) => _maxAvailableZoom = value),
        _controller!.getMinZoomLevel().then((value) => _minAvailableZoom = value),
        _controller!.setFocusMode(FocusMode.auto),
        _controller!.setFlashMode(FlashMode.off),
      ]);
      
      _currentResolution = newResolution;
      // 保存设置
      await _saveResolution(newResolution);
      
      if (mounted) {
        setState(() {
          _isInitialized = true;
          _previewSize = _controller!.value.previewSize;
        });
      }

      if (wasRecording && mounted) {
        await _toggleRecording();
      }
    } catch (e) {
      _showErrorDialog('切换清晰度失败: $e');
    }
  }

  // 修改清晰度选择器的字体大小
  void _showResolutionPicker() {
    if (_isRecording.value) {
      _showErrorDialog('录制过程中无法切换清晰度');
      return;
    }

    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          title: const Text(
            '选择视频清晰度',
            style: TextStyle(fontSize: 13),
          ),
          message: const Text(
            '更高清晰度需要更多存储空间',
            style: TextStyle(fontSize: 12),
          ),
          actions: _resolutionMap.entries.map((entry) {
            final bool isSelected = entry.key == _currentResolution;
            return CupertinoActionSheetAction(
              onPressed: () {
                Navigator.pop(context);
                _changeResolution(entry.key);
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    entry.value,
                    style: TextStyle(
                      color: isSelected ? CupertinoColors.systemBlue : null,
                      fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
                      fontSize: 13,
                    ),
                  ),
                  if (isSelected)
                    const Padding(
                      padding: EdgeInsets.only(left: 6),
                      child: Icon(
                        CupertinoIcons.checkmark_circle_fill,
                        color: CupertinoColors.systemBlue,
                        size: 14,
                      ),
                    ),
                ],
              ),
            );
          }).toList(),
          cancelButton: CupertinoActionSheetAction(
            isDestructiveAction: true,
            onPressed: () => Navigator.pop(context),
            child: const Text(
              '取消',
              style: TextStyle(fontSize: 13),
            ),
          ),
        );
      },
    );
  }

  // 优化曝光调整方法
  void _onExposureDragUpdate(DragUpdateDetails details) {
    // 计算曝光值变化，向上滑动增加曝光，向下滑动减少曝光
    double delta = details.primaryDelta! * -0.01;
    double newExposureOffset = _currentExposureOffset + delta;
    
    // 确保曝光值在允许范围内
    newExposureOffset = newExposureOffset.clamp(_minAvailableExposure, _maxAvailableExposure);
    
    if (newExposureOffset != _currentExposureOffset) {
      setState(() {
        _currentExposureOffset = newExposureOffset;
      });
      
      // 设置相机曝光
      try {
        _controller!.setExposureOffset(newExposureOffset);
        debugPrint('设置曝光值: $newExposureOffset');
      } catch (e) {
        debugPrint('设置曝光值失败: $e');
      }
    }
  }

  // 添加自动对焦和曝光优化方法
  void _startAutoFocusAndExposureOptimization() {
    // 取消之前的定时器
    _autoOptimizationTimer?.cancel();
    
    // 创建新的定时器，每5秒优化一次对焦和曝光
    _autoOptimizationTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
      if (_controller != null && _controller!.value.isInitialized && mounted && !_isExposureAdjusting) {
        _optimizeFocusAndExposure();
      }
    });
  }

  Future<void> _optimizeFocusAndExposure() async {
    try {
      // 先切换到自动对焦模式
      await _controller!.setFocusMode(FocusMode.auto);
      
      // 设置对焦点为中心点
      await _controller!.setFocusPoint(const Offset(0.5, 0.5));
      
      // 设置自动曝光模式
      await _controller!.setExposureMode(ExposureMode.auto);
      
      // 设置曝光点为中心点
      await _controller!.setExposurePoint(const Offset(0.5, 0.5));
      
      // 等待对焦和曝光调整完成
      await Future.delayed(const Duration(milliseconds: 800));
      
      // 保持自动对焦和曝光模式
      if (_controller != null && mounted) {
        await _controller!.setFocusMode(FocusMode.auto);
        await _controller!.setExposureMode(ExposureMode.auto);
      }
      
      debugPrint('自动优化对焦和曝光完成');
    } catch (e) {
      debugPrint('自动优化对焦和曝光失败: $e');
    }
  }
}

// 添加自定义画笔类
class FocusMarkerPainter extends CustomPainter {
  final Color color;
  final double strokeWidth;

  FocusMarkerPainter({
    required this.color,
    this.strokeWidth = 1.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke;

    final center = Offset(size.width / 2, size.height / 2);
    final length = size.width * 0.2; // 十字线长度

    // 绘制水平线
    canvas.drawLine(
      Offset(center.dx - length, center.dy),
      Offset(center.dx + length, center.dy),
      paint,
    );

    // 绘制垂直线
    canvas.drawLine(
      Offset(center.dx, center.dy - length),
      Offset(center.dx, center.dy + length),
      paint,
    );

    // 绘制四个角
    final cornerLength = size.width * 0.15;
    final margin = size.width * 0.1;

    // 左上角
    canvas.drawLine(
      Offset(margin, margin),
      Offset(margin + cornerLength, margin),
      paint,
    );
    canvas.drawLine(
      Offset(margin, margin),
      Offset(margin, margin + cornerLength),
      paint,
    );

    // 右上角
    canvas.drawLine(
      Offset(size.width - margin, margin),
      Offset(size.width - margin - cornerLength, margin),
      paint,
    );
    canvas.drawLine(
      Offset(size.width - margin, margin),
      Offset(size.width - margin, margin + cornerLength),
      paint,
    );

    // 左下角
    canvas.drawLine(
      Offset(margin, size.height - margin),
      Offset(margin + cornerLength, size.height - margin),
      paint,
    );
    canvas.drawLine(
      Offset(margin, size.height - margin),
      Offset(margin, size.height - margin - cornerLength),
      paint,
    );

    // 右下角
    canvas.drawLine(
      Offset(size.width - margin, size.height - margin),
      Offset(size.width - margin - cornerLength, size.height - margin),
      paint,
    );
    canvas.drawLine(
      Offset(size.width - margin, size.height - margin),
      Offset(size.width - margin, size.height - margin - cornerLength),
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
} 